

****DEFINE GROUPS**** (ENABLES SKEWNESS ESTIMATES TO RUN MUCH MORE QUICKLY)
use PERMNO date RET DLRET DLSTCD using "$jfqa_rep/crsp_daily_all", clear

qui{
rename PERMNO permno
rename RET ret
rename DLSTCD dlstcd
rename DLRET dlret

drop if missing(ret)

*de-listed returns
replace ret=dlret if missing(ret)
replace ret=-0.3 if missing(ret) & dlstcd==500
replace ret=-0.3 if missing(ret) & dlstcd==520
replace ret=-0.3 if missing(ret) & dlstcd>550 & dlstcd<575
replace ret=-0.3 if missing(ret) & dlstcd==580
replace ret=-0.3 if missing(ret) & dlstcd==584
replace ret=-1 if missing(ret) & ~missing(dlstcd)
drop dlstcd dlret

gen year=year(date)
gen month=month(date)
gen day=day(date)

sort permno date
drop if permno==permno[_n-1] & date==date[_n-1]

drop date

preserve

tempfile copy

keep permno

drop if permno==permno[_n-1]

duplicates drop

egen permno_group=xtile(permno), nq(100)

save `copy'

restore 

merge m:1 permno using `copy'
drop _merge

}
save "$jfqa_rep/12_Skew_Groups.dta", replace


***ESTIMATE SKEWNESS***
qui{
forval j=1/100 {
use "$jfqa_rep/12_Skew_Groups.dta", clear

keep if permno_group==`j'

gen year1=year
replace year1=year1-1 if month==1
gen year2=year1
replace year2=year2-1 if month==2
gen year3=year2
replace year3=year3-1 if month==3
gen year4=year3
replace year4=year4-1 if month==4
gen year5=year4
replace year5=year5-1 if month==5
gen year6=year5
replace year6=year6-1 if month==6
gen year7=year6
replace year7=year7-1 if month==7
gen year8=year7
replace year8=year8-1 if month==8
gen year9=year8
replace year9=year9-1 if month==9
gen year10=year9
replace year10=year10-1 if month==10
gen year11=year10
replace year11=year11-1 if month==11
gen year12=year

gen skew=.

forval i=1/12 {
	rangestat (skewness) ret, interval(year`i' -1 1) by(permno year`i')
	replace skew=ret_skewness if month==`i'
	drop ret_skewness year`i'
}

collapse skew, by(permno year month)

save "$jfqa_rep/12_Skew_`j'.dta", replace
}
}

use "$jfqa_rep/12_Skew_1.dta", clear

forval i=2/100 {
append using "$jfqa_rep/12_Skew_`i'.dta"
}

/*
forval i==1/100 {
	rm "$jfqa_rep/12_Skew_`i'.dta"
}
rm "$jfqa_rep/12_Skew_Groups.dta"
*/

gen monthyear=ym(year, month)

tsset permno monthyear
sort permno monthyear

gen lag_skew=L.skew

save "$jfqa_rep/12_Skew.dta", replace
